package com.jian.mall.produce.service.impl;

import com.jian.mall.common.content.AttrTypeEnum;
import com.jian.mall.produce.dao.AttrAttrgroupRelationDao;
import com.jian.mall.produce.dao.AttrGroupDao;
import com.jian.mall.produce.dao.CategoryDao;
import com.jian.mall.produce.entity.AttrAttrgroupRelationEntity;
import com.jian.mall.produce.entity.AttrGroupEntity;
import com.jian.mall.produce.entity.CategoryEntity;
import com.jian.mall.produce.service.CategoryService;
import com.jian.mall.produce.vo.AttrGroupRelationVo;
import com.jian.mall.produce.vo.AttrRepsVo;
import com.jian.mall.produce.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jian.mall.common.utils.PageUtils;
import com.jian.mall.common.utils.Query;

import com.jian.mall.produce.dao.AttrDao;
import com.jian.mall.produce.entity.AttrEntity;
import com.jian.mall.produce.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private AttrAttrgroupRelationDao relationDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper =
                new QueryWrapper<AttrEntity>().eq("attr_type",
                        "base".equalsIgnoreCase(type) ? AttrTypeEnum.ATTR_TYPE_BASE.getCode() : AttrTypeEnum.ATTR_TYPE_SALE.getCode());
        if (catelogId > 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.and((qw) -> qw.eq("attr_id", key).or().like("attr_name", key));
        }
        IPage<AttrEntity> page = page(new Query<AttrEntity>().getPage(params), queryWrapper);

        // 将page里面的分组 分类信息查询出来填充
        List<AttrRepsVo> list = page.getRecords().stream().map((item) -> {
                    AttrRepsVo repsVo = new AttrRepsVo();
                    BeanUtils.copyProperties(item, repsVo);

                    if ("base".equalsIgnoreCase(type)) {
                        AttrAttrgroupRelationEntity entity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().
                                eq("attr_id", repsVo.getAttrId()));
                        if (entity != null) {
                            AttrGroupEntity groupEntity = attrGroupDao.selectById(entity.getAttrGroupId());
                            // 设置分组名字
                            repsVo.setGroupName(groupEntity.getAttrGroupName());
                        }
                    }

                    // 设置分类名字
                    CategoryEntity categoryEntity = categoryDao.selectById(item.getCatelogId());
                    if (categoryEntity != null)
                        repsVo.setCatelogName(categoryEntity.getName());
                    return repsVo;
                }).
                collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(list);
        return pageUtils;
    }

    @Override
    public AttrRepsVo getInfoById(Long attrId) {
        AttrRepsVo attrRepsVo = new AttrRepsVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrRepsVo);

        AttrAttrgroupRelationEntity relationEntity =
                relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));

        if (relationEntity != null) {
            AttrGroupEntity groupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
            if (groupEntity != null)
                attrRepsVo.setGroupName(groupEntity.getAttrGroupName());
        }

        CategoryEntity categoryEntity = categoryDao.selectById(attrRepsVo.getCatelogId());
        if (categoryEntity != null) {
            attrRepsVo.setCatelogName(categoryEntity.getName());
            Long[] categoryPath = categoryService.findCategoryPath(categoryEntity.getCatId());
            attrRepsVo.setCatelogPath(categoryPath);
        }
        return attrRepsVo;
    }

    @Transactional
    @Override
    public void updateVo(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        updateById(attrEntity);

        if (attr.getAttrType().equals(AttrTypeEnum.ATTR_TYPE_BASE.getCode())) {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            entity.setAttrId(attr.getAttrId());
            entity.setAttrGroupId(attr.getAttrGroupId());
            if (0 == relationDao.selectCount(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()))) {
                relationDao.insert(entity);
            } else {
                relationDao.updateById(entity);
            }
        }
    }

    @Override
    public void saveInfo(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        save(attr);

        if (attr.getAttrType().equals(AttrTypeEnum.ATTR_TYPE_BASE.getCode()) && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationDao.insert(relationEntity);
        }
    }

    @Override
    public void removeInfoByIds(List<Long> asList) {
        removeByIds(asList);
        asList.forEach((id) -> relationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", id)));
    }

    @Override
    public List<AttrEntity> selectListByGroupId(Long groupId) {

        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id", groupId));

        if (relationEntities == null) {
            return null;
        }

        List<Long> collect = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        List<AttrEntity> attrEntities = new ArrayList<>();
        if (collect.size() > 0)
            attrEntities = baseMapper.selectBatchIds(collect);

        return attrEntities;
    }

    @Override
    public void deleteByAttrIdAndRelationIds(AttrGroupRelationVo[] attrGroupRelationVos) {
        List<AttrAttrgroupRelationEntity> collect = Arrays.stream(attrGroupRelationVos).map((item) -> {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            entity.setAttrId(item.getAttrId());
            entity.setAttrGroupId(item.getAttrGroupId());
            return entity;
        }).collect(Collectors.toList());
        relationDao.deleteBatchRelation(collect);
    }

    @Override
    public PageUtils selectListNotRelation(Map<String, Object> params, Long groupId) {
        AttrGroupEntity groupEntity = attrGroupDao.selectById(groupId);
        if (groupEntity == null) {
            return null;
        }
        Long catelogId = groupEntity.getCatelogId();
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(null);
        List<Long> list = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId);
        if (list.size() > 0) {
            wrapper.notIn("attr_id", list);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        wrapper.eq("attr_type", AttrTypeEnum.ATTR_TYPE_BASE.getCode());
        IPage<AttrEntity> iPage = baseMapper.selectPage(new Query<AttrEntity>().getPage(params), wrapper);
        return new PageUtils(iPage);
    }

    @Override
    public List<Long> selectNeedSearchByAttrIds(List<Long> attrIds) {
        List<Long> ids = baseMapper.selectNeedSearchByAttrIds(attrIds);
        return ids;
    }

}